package com.yejiali.backend.exception;

import com.yejiali.backend.common.httpcode.HttpCodeEnum;
import com.yejiali.backend.response.Response;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:yejiali
 * @Date:2025/5/10-05-10-18:22
 * @Decsription:com.yejiali.backend.exception
 * @Version:1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 对请求参数校验异常进行统一处理
     * @param ex
     * @return
     */

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleValidationException(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.toList());
        return Response.error(401,  errors.get(0));// 返回第一个错误信息
    }
    /**
     * 对非Controller层参数校验异常进行统一处理
     * @param ex
     * @return
     * */
    @ExceptionHandler(ConstraintViolationException.class)
    public Response handleConstraintViolation(ConstraintViolationException ex) {
        /*List<String> errors = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());*/
        return Response.error(402, "参数错误");
    }

    @ExceptionHandler(SystemException.class)
    public Response handleException(SystemException e) {
            //打印异常信息
            log.error("自定义异常",e);
            //从异常对象中获取提示信息 封装返回
            return Response.error(e.getCode(), e.getMsg());

        }

    @ExceptionHandler(Exception.class)
    public Response exceptionHandler(Exception e){
        //打印异常信息
        log.error("出现了异常！{}",e);
        //从异常对象中获取提示信息 封装返回
        return Response.error(HttpCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());

    }
}
